package models

import (
	"time"

	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

const timeFormat = "2006-01-02 15:04:05"
const timezone = "Asia/Shanghai"

type BaseModel struct {
	ID        uint           `gorm:"primarykey"`
	CreatedAt string         `gorm:"column:created_at;type:varchar(22);default:''"`
	UpdatedAt string         `gorm:"column:updated_at;type:varchar(22);default:''"`
	DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp;index"`
}

func (u *BaseModel) BeforeCreate(tx *gorm.DB) error {
	u.CreatedAt = time.Now().Format(timeFormat)
	u.UpdatedAt = time.Now().Format(timeFormat)
	return nil
}

// 在更新前设置时间
func (u *BaseModel) BeforeUpdate(tx *gorm.DB) error {
	u.UpdatedAt = time.Now().Format(timeFormat)
	return nil
}

type MyDecimal decimal.Decimal

func (d MyDecimal) GormDataType() string {
	return "decimal(12,2)"
}

// 将float64转换为MyDecimal
func FromFloat(f float64) MyDecimal {
	return MyDecimal(decimal.NewFromFloat(f))
}

// 将MyDecimal转换为float64
func (d MyDecimal) Float64() float64 {
	return decimal.Decimal(d).InexactFloat64()
}

// 将MyDecimal转换为字符串
func (d MyDecimal) String() string {
	return decimal.Decimal(d).String()
}
